package net.xiangcaowuyu.redis.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 * @author laughing
 * @date 2020/10/2
 * @site https://www.xiangcaowuyu.net
 */
@Component
public class RedisUtils {

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 判断是否存在
     *
     * @return
     */
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 获取值
     * @param key
     * @return
     */
    public Object getValue(String key){
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 设置值
     *
     * @param key
     * @param value
     */
    public void setValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 获取过期时间
     *
     * @param key
     * @return
     */
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key);
    }

    /**
     * 获取过期时间
     *
     * @param key
     * @param timeUnit
     * @return
     */
    public Long getExpire(String key, TimeUnit timeUnit) {
        return redisTemplate.getExpire(key, timeUnit);
    }

    /**
     * 设置过期时间
     *
     * @param key
     * @param timeOut
     * @return
     */
    public Boolean setExpire(String key, Duration timeOut) {
        return redisTemplate.expire(key, timeOut);
    }

    /**
     * 删除
     *
     * @param key
     * @return
     */
    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 删除
     * @param keys
     * @return
     */
    public Long deleteAll(List<String> keys){
        return redisTemplate.delete(keys);
    }

}
